import XEUtils from 'xe-utils';
import { formatterNumberOrDate } from './table-utils'


// ------ render
const mateRegRule = /#{(.+?)\}/;
const mateRegRules = /#{(.+?)\}/g;
/**
 * 一个超链接渲染超链接的方法
 * 1 网址
 * linkUrl: http://www.baidu.com
 * 2 路由地址
 * linkUrl: /home
 *
 * 参数解析：
 *  示例1：http://www.baidu.com?id=#{id}&name=#{name}
 *  示例2：/home?id=#{id}&name=#{name}
 *
 * @param {Object} param { row, column }
 * @param {Object} extParams 其他参数
 * @returns String | Dom
 */
export const linkUrlRender = ({ row, column }, extParams) => {
  const { format, linkUrl } = extParams
  const cellValue = row[column.field]
  const finallValue = formatterNumberOrDate(cellValue, format)
  if (linkUrl && cellValue) {
    let finalLinkUrl = linkUrl
    const marks = finalLinkUrl.match(mateRegRules);
    if (marks) {
      const markKeys = marks.map(item => item.match(mateRegRule)[1]);
      markKeys.forEach(key => { finalLinkUrl = finalLinkUrl.replace(mateRegRule, row[key] || '') });
    }
    return [
      <a
        class='rk-grid-row-link'
        target='_blank'
        rel='noopener'
        href={finalLinkUrl}>
        {finallValue}
      </a>
    ]
  } else {
    return finallValue
  }
}

// ------ formatter
/**
 * 数字或日期格式化
 *
 * @param {Object} param 参数信息 { cellValue, row, column }
 * @param {String} rule 格式化规则
 * @returns 格式化后的数据
 */
export const numberOrDateFormatter = ({ cellValue, column }, rule) => {
  return formatterNumberOrDate(cellValue, rule)
}
